<template>
  <div class="retake-calendar">
    <el-row :gutter="20" class="calendar-header">
      <el-col :span="6">
        <el-date-picker
          v-model="currentMonth"
          type="month"
          placeholder="选择月份"
          value-format="yyyy-MM"
          @change="handleMonthChange"
        />
      </el-col>
      <el-col :span="6">
        <el-button-group>
          <el-button @click="prevMonth" icon="el-icon-arrow-left">上月</el-button>
          <el-button @click="nextMonth" icon="el-icon-arrow-right">下月</el-button>
        </el-button-group>
      </el-col>
      <el-col :span="6">
        <el-button @click="goToday" type="primary">今天</el-button>
      </el-col>
      <el-col :span="6">
        <el-button @click="refresh" icon="el-icon-refresh">刷新</el-button>
      </el-col>
    </el-row>

    <div class="calendar-container">
      <div class="calendar-grid">
        <!-- 星期标题 -->
        <div class="calendar-weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        
        <!-- 日期网格 -->
        <div class="calendar-days">
          <div 
            v-for="(day, index) in calendarDays" 
            :key="index"
            :class="getDayClass(day)"
            @click="handleDayClick(day)"
          >
            <div class="day-number">{{ day.date }}</div>
            <div class="day-events">
              <div 
                v-for="event in day.events" 
                :key="event.retakeId"
                :class="['event-item', getEventClass(event)]"
                @click.stop="handleEventClick(event)"
              >
                <div class="event-time">{{ formatTime(event.scheduledTime) }}</div>
                <div class="event-title">{{ event.studentName }}</div>
                <div class="event-subject">{{ event.subjectName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 事件详情弹窗 -->
    <el-dialog title="补考详情" :visible.sync="eventDialogVisible" width="500px">
      <div v-if="selectedEvent">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学员姓名">{{ selectedEvent.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ selectedEvent.studentNo }}</el-descriptions-item>
          <el-descriptions-item label="科目">{{ selectedEvent.subjectName }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedEvent.status)">
              {{ selectedEvent.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="安排时间" :span="2">
            {{ parseTime(selectedEvent.scheduledTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedEvent.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eventDialogVisible = false">关 闭</el-button>
        <el-button 
          v-if="selectedEvent && selectedEvent.status === '待考试'"
          type="primary" 
          @click="handleCompleteEvent"
        >标记完成</el-button>
        <el-button 
          v-if="selectedEvent && selectedEvent.status === '待考试'"
          type="danger" 
          @click="handleCancelEvent"
        >取消安排</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRetakeScheduleByDateRange, completeRetakeSchedule, cancelRetakeSchedule } from "@/api/jiaxiao/retake";

export default {
  name: "RetakeCalendar",
  data() {
    return {
      currentMonth: "",
      calendarDays: [],
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],
      eventDialogVisible: false,
      selectedEvent: null,
      retakeData: []
    };
  },
  created() {
    this.initCurrentMonth();
    this.loadCalendarData();
  },
  methods: {
    /** 初始化当前月份 */
    initCurrentMonth() {
      const now = new Date();
      this.currentMonth = this.formatMonth(now);
    },
    /** 加载日历数据 */
    loadCalendarData() {
      const startDate = this.getMonthStartDate();
      const endDate = this.getMonthEndDate();
      
      getRetakeScheduleByDateRange(
        this.formatDate(startDate, 'yyyy-MM-dd'),
        this.formatDate(endDate, 'yyyy-MM-dd')
      ).then(response => {
        this.retakeData = response.data || [];
        this.generateCalendar();
      });
    },
    /** 生成日历 */
    generateCalendar() {
      const startDate = this.getMonthStartDate();
      const endDate = this.getMonthEndDate();
      const days = [];
      
      // 获取月份第一天是星期几
      const firstDay = startDate.getDay();
      
      // 添加上个月的末尾几天（用于填充第一周）
      for (let i = firstDay - 1; i >= 0; i--) {
        const date = new Date(startDate);
        date.setDate(date.getDate() - i - 1);
        days.push({
          date: date.getDate(),
          fullDate: new Date(date),
          isCurrentMonth: false,
          events: []
        });
      }
      
      // 添加当前月的所有日期
      const currentDate = new Date(startDate);
      while (currentDate <= endDate) {
        const dayEvents = this.getEventsForDate(currentDate);
        days.push({
          date: currentDate.getDate(),
          fullDate: new Date(currentDate),
          isCurrentMonth: true,
          events: dayEvents
        });
        currentDate.setDate(currentDate.getDate() + 1);
      }
      
      // 添加下个月的开头几天（用于填充最后一周）
      const lastDay = endDate.getDay();
      for (let i = 1; i <= 6 - lastDay; i++) {
        const date = new Date(endDate);
        date.setDate(date.getDate() + i);
        days.push({
          date: date.getDate(),
          fullDate: new Date(date),
          isCurrentMonth: false,
          events: []
        });
      }
      
      this.calendarDays = days;
    },
    /** 获取指定日期的事件 */
    getEventsForDate(date) {
      const dateStr = this.formatDate(date, 'yyyy-MM-dd');
      return this.retakeData.filter(event => {
        const eventDate = this.formatDate(new Date(event.scheduledTime), 'yyyy-MM-dd');
        return eventDate === dateStr;
      });
    },
    /** 获取日期样式类 */
    getDayClass(day) {
      const classes = ['calendar-day'];
      
      if (!day.isCurrentMonth) {
        classes.push('other-month');
      }
      
      if (this.isToday(day.fullDate)) {
        classes.push('today');
      }
      
      if (day.events.length > 0) {
        classes.push('has-events');
      }
      
      return classes.join(' ');
    },
    /** 获取事件样式类 */
    getEventClass(event) {
      const classes = ['event'];
      
      switch(event.status) {
        case '待考试':
          classes.push('pending');
          break;
        case '已完成':
          classes.push('completed');
          break;
        case '已取消':
          classes.push('cancelled');
          break;
      }
      
      return classes.join(' ');
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      switch(status) {
        case '待考试': return 'warning';
        case '已完成': return 'success';
        case '已取消': return 'danger';
        default: return '';
      }
    },
    /** 判断是否为今天 */
    isToday(date) {
      const today = new Date();
      return date.getDate() === today.getDate() &&
             date.getMonth() === today.getMonth() &&
             date.getFullYear() === today.getFullYear();
    },
    /** 格式化时间 */
    formatTime(dateTime) {
      const date = new Date(dateTime);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    /** 格式化月份 */
    formatMonth(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      return `${year}-${month}`;
    },
    /** 格式化日期 */
    formatDate(date, fmt) {
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    },
    /** 获取月份开始日期 */
    getMonthStartDate() {
      const [year, month] = this.currentMonth.split('-');
      return new Date(year, month - 1, 1);
    },
    /** 获取月份结束日期 */
    getMonthEndDate() {
      const [year, month] = this.currentMonth.split('-');
      return new Date(year, month, 0);
    },
    /** 月份变化 */
    handleMonthChange() {
      this.loadCalendarData();
    },
    /** 上个月 */
    prevMonth() {
      const date = new Date(this.currentMonth + '-01');
      date.setMonth(date.getMonth() - 1);
      this.currentMonth = this.formatMonth(date);
      this.loadCalendarData();
    },
    /** 下个月 */
    nextMonth() {
      const date = new Date(this.currentMonth + '-01');
      date.setMonth(date.getMonth() + 1);
      this.currentMonth = this.formatMonth(date);
      this.loadCalendarData();
    },
    /** 回到今天 */
    goToday() {
      this.currentMonth = this.formatMonth(new Date());
      this.loadCalendarData();
    },
    /** 刷新 */
    refresh() {
      this.loadCalendarData();
    },
    /** 日期点击 */
    handleDayClick(day) {
      console.log('Day clicked:', day);
    },
    /** 事件点击 */
    handleEventClick(event) {
      this.selectedEvent = event;
      this.eventDialogVisible = true;
    },
    /** 完成事件 */
    handleCompleteEvent() {
      completeRetakeSchedule(this.selectedEvent.retakeId).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.eventDialogVisible = false;
        this.loadCalendarData();
      });
    },
    /** 取消事件 */
    handleCancelEvent() {
      this.$modal.confirm('确认取消这个补考安排？').then(() => {
        cancelRetakeSchedule(this.selectedEvent.retakeId).then(() => {
          this.$modal.msgSuccess("操作成功");
          this.eventDialogVisible = false;
          this.loadCalendarData();
        });
      });
    }
  }
};
</script>

<style scoped>
.retake-calendar {
  padding: 20px;
}

.calendar-header {
  margin-bottom: 20px;
}

.calendar-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.calendar-grid {
  display: flex;
  flex-direction: column;
}

.calendar-weekdays {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.weekday {
  flex: 1;
  padding: 12px;
  text-align: center;
  font-weight: bold;
  color: #606266;
}

.calendar-days {
  display: flex;
  flex-wrap: wrap;
}

.calendar-day {
  flex: 0 0 calc(100% / 7);
  min-height: 120px;
  border-right: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calendar-day:hover {
  background-color: #f5f7fa;
}

.calendar-day.other-month {
  background-color: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background-color: #e6f7ff;
}

.calendar-day.has-events {
  background-color: #fff7e6;
}

.day-number {
  font-weight: bold;
  margin-bottom: 4px;
}

.day-events {
  max-height: 80px;
  overflow-y: auto;
}

.event-item {
  margin-bottom: 2px;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.event-item:hover {
  transform: scale(1.02);
}

.event-item.pending {
  background-color: #fff7e6;
  border-left: 3px solid #faad14;
}

.event-item.completed {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.event-item.cancelled {
  background-color: #fff2f0;
  border-left: 3px solid #ff4d4f;
}

.event-time {
  font-weight: bold;
  color: #1890ff;
}

.event-title {
  font-weight: bold;
  color: #262626;
}

.event-subject {
  color: #8c8c8c;
}

.dialog-footer {
  text-align: right;
}
</style>
